package com.zhike.service.messages.impl;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Repository;

import com.zhike.common.enums.YesNoEnum;
import com.zhike.common.repository.ClearMessage;
import com.zhike.common.repository.HistoryMessage;
import com.zhike.service.messages.IClearMessageRepository;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import lombok.extern.slf4j.Slf4j;

@Repository
@Slf4j
public class ClearMessageRepository implements IClearMessageRepository {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveClearMessage(ClearMessage clearMessage) {
        try {
            mongoTemplate.insert(clearMessage);
        } catch (Exception e) {
            log.error("save clearMessage err: {}", e.getMessage());
        }
    }

    public Collection<ClearMessage> batchSaveClearMessage(List<ClearMessage> cms) {
        try {
            Collection<ClearMessage> ms = mongoTemplate.insertAll(cms);
            return ms;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ClearMessage findAndModifyClearRecord(String sessionId, String userId) {
        Update update = new Update().set("timestamp", new Date());
        Query query = new Query(
                Criteria.where("sessionId").is(sessionId)
                        .and("userId").is(userId));
        return mongoTemplate.findAndModify(query, update, ClearMessage.class);
    }

    @Override
    public ClearMessage getClearRecord(String sessionId, String userId) {
        Query query = new Query(
                Criteria.where("sessionId").is(sessionId)
                        .and("userId").is(userId)
                        .and("status").is(0));
        return mongoTemplate.findOne(query, ClearMessage.class);
    }

    @Override
    public List<ClearMessage> getDeleteRecord(String sessionId, String userId, Integer status) {
        Query query = new Query(
                Criteria.where("sessionId").is(sessionId)
                        .and("userId").is(userId)
                        .and("status").is(status));
        return mongoTemplate.find(query, ClearMessage.class);
    }

    
}
